package com.eet.juc.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁Demo
 *
 * @author zheng.zhang
 */
@SuppressWarnings("all")
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        // 五个线程写入数据
        for (int i = 1; i <= 5; i++) {
            final String temp = String.valueOf(i);
            new Thread(() -> MyCacheLock.put(temp, temp), "写入: " + String.valueOf(i)).start();
        }

        // 五个线程读取数据
        for (int i = 1; i <= 5; i++) {
            final String temp = String.valueOf(i);
            new Thread(() -> MyCacheLock.get(temp), "读取: " + String.valueOf(i)).start();
        }
    }
}

/**
 * 自定义一级缓存
 */
class MyCacheLock {
    private static volatile Map<String, Object> CACHE = new HashMap<>();
    private static final ReadWriteLock READ_WRITE_LOCK = new ReentrantReadWriteLock();

    /**
     * 写入数据
     *
     * @param key   键
     * @param value 值
     */
    public static void put(String key, Object value) {
        Lock writeLock = READ_WRITE_LOCK.writeLock();
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName().concat("->写入" + key));
            CACHE.put(key, value);
            System.out.println(Thread.currentThread().getName().concat("->写入成功"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    /**
     * 读出数据
     *
     * @param key 键
     * @return 返回实体数据
     */
    public static Object get(String key) {
        Lock readLock = READ_WRITE_LOCK.readLock();
        Object o = null;
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName().concat("->读取" + key));
            o = CACHE.get(key);
            System.out.println(Thread.currentThread().getName().concat("->读取成功"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
        return o;
    }
}

/**
 * 自定义一级缓存
 */
class MyCache {
    private static volatile Map<String, Object> cache = new HashMap<>();

    /**
     * 写入数据
     *
     * @param key   键
     * @param value 值
     */
    public static void put(String key, Object value) {
        System.out.println(Thread.currentThread().getName().concat("->写入" + key));
        cache.put(key, value);
        System.out.println(Thread.currentThread().getName().concat("->写入成功"));
    }

    /**
     * 读出数据
     *
     * @param key 键
     * @return 返回实体数据
     */
    public static Object get(String key) {
        System.out.println(Thread.currentThread().getName().concat("->读取" + key));
        Object o = cache.get(key);
        System.out.println(Thread.currentThread().getName().concat("->读取成功"));
        return o;
    }
}